﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ApiGateWay.Models;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Ocelot.Administration;
using Ocelot.Cache.CacheManager;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using Ocelot.Provider.Polly;

namespace ApiGateWay
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Identity Server Bear Tokens
            var identityServiceConfig = new IdentityServiceConfig();
            Configuration.GetSection("IdentityService").Bind(identityServiceConfig); // 获取配置信息

            Action<IdentityServerAuthenticationOptions> isaOpt = options =>
                {
                    options.Authority = identityServiceConfig.Uri;
                    options.RequireHttpsMetadata = identityServiceConfig.UseHttps;
                    options.ApiName = identityServiceConfig.ApiName;
                    options.ApiSecret = identityServiceConfig.ApiSecret;
                    options.SupportedTokens = SupportedTokens.Both;
                };
            services.AddAuthentication().AddIdentityServerAuthentication(identityServiceConfig.DefaultScheme, isaOpt);

            services.AddOcelot(Configuration)
                .AddConsul() // 使用consul发现
                .AddCacheManager(x => x.WithDictionaryHandle()) // 使用缓存
                .AddPolly() // 异常处理
                .AddAdministration("/administration", isaOpt); // 添加Ocelot路径管理 {adminPath}/connect/token
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc(Configuration["Swagger:Name"], new Swashbuckle.AspNetCore.Swagger.Info { Title = Configuration["Swagger:Title"], Version = Configuration["Swagger:Version"] });
            });
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                //app.UseHsts();
            }

            var apis = Configuration["Apis:SwaggerNames"].Split(";").ToList();
            app.UseMvc()
                .UseSwagger()
                .UseSwaggerUI(options =>
                {
                    apis.ForEach(key =>
                    {
                        options.SwaggerEndpoint($"/{key}/swagger.json", key);
                    });
                    options.DocumentTitle = "网关";
                });
            app.UseOcelot().Wait();
        }
    }
}
